package cn.itsource.ymcc.controller;

import cn.itsource.ymcc.config.AlicloudOSSProperties;
import cn.itsource.ymcc.constant.IdempotentConstants;
import cn.itsource.ymcc.domain.vo.SmsVo;
import cn.itsource.ymcc.result.JsonResult;
import cn.itsource.ymcc.service.ICommonService;
import cn.itsource.ymcc.util.CodeGenerateUtils;
import cn.itsource.ymcc.util.StrUtils;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.File;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

@RestController
@RequestMapping("/common/verifycode")
public class CommonController {
    @Autowired
    private ICommonService commonService;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @GetMapping("/createToken/{courseId}")
    public JsonResult createToken(@PathVariable("courseId")String courseId){
        String code = StrUtils.getComplexRandomString(32);
        redisTemplate.opsForValue().set(IdempotentConstants.IDEMPOTENT + courseId,code);
        return JsonResult.success().setData(code);
    }

    @GetMapping("/imageCode/{key}")
    public JsonResult createImageCode(@PathVariable("key") String key){
        return commonService.createImageCode(key);
    }

    @PostMapping("/sendSmsCode")
    public JsonResult sendSmsCode(@RequestBody @Valid SmsVo smsVo){
        return commonService.sendSmsCode(smsVo);
    }

    @Autowired
    private AlicloudOSSProperties properties;

    /**
     * 获取     令牌
     * @return
     */
    @GetMapping("/oss/sign")
    public JsonResult ossSign(){
        // host的格式为 bucketname.endpoint
        String host = "https://" + properties.getBucketName() + "." + properties.getEndpoint();
        // 用户上传文件时指定的前缀。不同的业务可以指定不同的前缀 用来做区分
        String dir = "itsource";
        // 创建OSSClient实例。
        OSS ossClient = null;
        try {
            //策略过期时间
            long expireTime = 100;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);

            // PostObject请求最大可支持的文件大小为5 GB，即CONTENT_LENGTH_RANGE为5*1024*1024*1024。
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            // 创建OSSClient实例。
            ossClient = new OSSClientBuilder()
                    .build(properties.getEndpoint(), properties.getAccessKey(), properties.getSecretKey());

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            //签名
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            //返回签名及OSS相关参数
            Map<String, String> respMap = new LinkedHashMap<String, String>();
            respMap.put("accessid", properties.getAccessKey());
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));

            return JsonResult.success().setData(respMap);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        } finally {
            if(ossClient != null){
                ossClient.shutdown();
            }
        }
        return null;
    }



//    public static void main(String[] args) {
//        // Endpoint 地域端点
//        String endpoint = "http://oss-cn-chengdu.aliyuncs.com";
//
//        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
//        String accessKeyId = "LTAI5tN1kFuXU4kHVBLeWs63";
//        String accessKeySecret = "g3OxLoXuGijI5EAZMCo8A6JdZXRB5Y";
//
//        // 创建OSSClient实例。
//        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
//
//        // 创建PutObjectRequest对象。 ，
//        PutObjectRequest putObjectRequest = new PutObjectRequest("ymcc-0310", "hhy.png",
//                new File("G:\\JAVA0310\\学习资料\\118699798_371443727587081_2298005209772399553_o.jpg"));
//
//        // 上传文件。
//        ossClient.putObject(putObjectRequest);
//
//        // 关闭OSSClient。
//        ossClient.shutdown();
//    }

}
